
#include "http.hxx"

#include <cstdlib>
#include <vector>

using std::map;
using std::string;
using std::vector;

namespace http {

////////////////////////////////////////////////////////////////////////////////

    string read_request(sock_inet_tcp& sock) {
        string line;

        sock >> line;

        vector<char> location(line.length());
        char version[2];

        if(sscanf(line.c_str(), "GET%*[ ]%[^ ]%*[ ]HTTP/1.%1[1]", location.data(), version) != 2) {
            throw bad_request_error();
        }

        return string(location.data());
    };

    string read_response(sock_inet_tcp& sock) {
        string line;

        sock >> line;

        vector<char> response(line.length());

        if(sscanf(line.c_str(), "HTTP/1.1%*[ ]%[^\n]", response.data()) != 1) {
            throw bad_response_error();
        }

        return string(response.data());
    };

    map<string,string> read_headers(sock_inet_tcp& sock) {
        string line;

        map<string,string> headers;

        for(string line; sock >> line && !line.empty(); ) {
            size_t delimiter;

            if((delimiter = line.find(": ")) == string::npos) {
                throw bad_request_error();
            }

            headers[line.substr(0, delimiter)] = line.substr(delimiter + 2);
        }

        return headers;
    };

    vector<char> read_body(sock_inet_tcp& sock, const map<string,string>& headers) {
        auto length = headers.find("Content-Length");

        if(length == headers.end()) {
            throw length_required_error();
        }

        vector<char> body(atoi(length->second.c_str()));

        sock >> body;

        return body;
    }

    void skip_body(sock_inet_tcp& sock, const map<string,string>& headers) {
        auto length = headers.find("Content-Length");

        if(length == headers.end()) {
            return;
        }

        vector<char> body(atoi(length->second.c_str()));

        sock >> body;
    }

////////////////////////////////////////////////////////////////////////////////

}
